package com.degratnik.plitki.fragments;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.degratnik.plitki.R;
import com.degratnik.plitki.adapters.PlitkiAdapter;
import com.degratnik.plitki.sql.data.Event;

public class Plitka extends Fragment {
	private static final boolean NOT_ATTACH_TO_ROOT = false;

	// https://www.google.com.ua/search?safe=on&site=imghp&tbm=isch&q=milk+buy

	/*
	 * <img class="rg_i" name="mB6GljwLqnKJ8M:"src=
	 * "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQV9vB_ekBhSppw3TwtHvyDU-BlKSL9OwLqHWMUcikK7P7j5-EuhA"
	 * data-sz="f" onload="google.stb.csi.onTbn(1, this)"style=
	 * "width: 231px; height: 154px; margin-left: -2px; margin-right: -3px; margin-top: 0px;"
	 * >
	 */

	private WebView web;
	private String query;

	private TextView title;
	private EditText details;
	
	private LinearLayout imageHolder;

	private ImageView image;

	private ArrayList<String> images = new ArrayList<String>();

	private PlitkiAdapter adapter;
	
	public static Event event;
	public static Drawable resultDrawable;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent,
			Bundle state) {
		View v = inflater.inflate(R.layout.plitka_edit, parent,
				NOT_ATTACH_TO_ROOT);

		images.clear();
		query = "https://www.google.com.ua/search?safe=on&site=imghp&tbm=isch&q=milk+buy";
		web = (WebView) v.findViewById(R.id.web);
		imageHolder = (LinearLayout) v.findViewById(R.id.imageHolder);
		image = (ImageView) v.findViewById(R.id.image);

		web.setWebViewClient(new WebViewClient() {
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				Log.i("web", String.format("Page error %s %s", description, failingUrl));
			}

			public void onPageFinished(WebView view, String url) {
				Log.i("web", String.format("Page loaded %s", url));

				Context c = getActivity();
				if (c != null) {
					ImageView pic = new ImageView(getActivity());
					pic.setImageResource(R.drawable.square_blue);
					addImageToHolder(pic);
					pic = new ImageView(getActivity());
					pic.setImageResource(R.drawable.square_green);
					addImageToHolder(pic);
					pic = new ImageView(getActivity());
					pic.setImageResource(R.drawable.square_red);
					addImageToHolder(pic);

					if (images.size() > 0) {
						DownloadHtmlTask task = new DownloadHtmlTask();
						task.execute(images.remove(0));
					}
				}
			}

			// you tell the webclient you want to catch when a url is about to
			// load
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return false;
			}

			// here you execute an action when the URL you want is about to load
			@Override
			public void onLoadResource(WebView view, String url) {
				Log.i("web link", String.format(url));
				if (url.compareTo(query) != 0) {
					images.add(url);
				}
			}
		});

		web.getSettings().setJavaScriptEnabled(true);
		web.getSettings().setDomStorageEnabled(true);
		//web.loadUrl(query);
		title = (TextView)v.findViewById(R.id.title);
		title.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				Log.i("Focus", String.format("title focus %s", hasFocus));
				String text = title.getText().toString();
				if (!hasFocus && text.length() > 0) {
					images.clear();
					imageHolder.removeAllViews();
					query = "https://www.google.com.ua/search?client=ms-android-google&hl=uk&site=webhp&tbm=isch&q="+text.replace(" ", "+");
					web.loadUrl(query);
				}
			}
		});
		
		details = (EditText)v.findViewById(R.id.details);
		title.setText(event.getTitle());
		details.setText(event.getDetails());
		
		android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
	    fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
	        @Override
	        public void onBackStackChanged() {
	        	event.setTitle(title.getText().toString());
	        	event.setDetails(details.getText().toString());
	        	getAdapter().saveEvent(event);
	        	getAdapter().notifyDataSetChanged();
	        }
	    });
		
		return v;
	}

	private void addImageToHolder(ImageView pic) {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		pic.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				image.setImageDrawable(((ImageView) v).getDrawable());
				resultDrawable = image.getDrawable();
			}
		});
		imageHolder.addView(pic, lp);

	}

	public PlitkiAdapter getAdapter() {
		return adapter;
	}

	public void setAdapter(PlitkiAdapter adapter) {
		this.adapter = adapter;
	}

	public class DownloadHtmlTask extends AsyncTask<String, Void, Bitmap> {

		@SuppressWarnings("unused")
		private String getHtml(String url) throws ClientProtocolException,
				IOException {
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = httpClient.execute(httpGet, localContext);
			String result = "";

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			String line = null;
			while ((line = reader.readLine()) != null) {
				result += line + "\n";
			}
			return result;
		}

		private Bitmap getJPEG(String url) {
			InputStream in;
			Bitmap bitmap = null;
			try {
				in = new java.net.URL(url).openStream();
				bitmap = BitmapFactory.decodeStream(in);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
					e.printStackTrace();
			}
			return bitmap;

		}

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap result = null;
			Log.i("get pic", String.format(params[0]));
			if (params[0] != null) {
				result = getJPEG(params[0]);
			}
			return result;
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);

			Context c = getActivity();

			if (result != null && c != null) {
				ImageView pic = new ImageView(c);
				pic.setImageBitmap(result);
				addImageToHolder(pic);
			}

			if (images.size() > 0 && c != null) {
				DownloadHtmlTask task = new DownloadHtmlTask();
				task.execute(images.remove(0));
			}
		}

	}
	

}
